import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { EntityManager } from 'typeorm';
import { Permission } from './entities/permission.entity';
import { User } from './entities/user.entity';
import { InjectEntityManager } from '@nestjs/typeorm';
import { LoginUserDto } from './dto/login-user.dto';

@Injectable()
export class UserService {

  //EntityManager 更容易实现复杂操作 
  //例如，在一个事务中，我们需要先创建一个用户，然后创建一个与该用户相关的订单，最后扣除用户的余额。
  //这个过程涉及到了三个数据库操作，需要进行协调和控制。

  //useRepository 也支持事务操作。在 Nest.js 中，我们可以使用 @Transaction 装饰器来开启事务
  //缺点是功能相对较为有限，只能进行简单的 CRUD 操作和事务操作，不支持复杂的事务操作等。
  @InjectEntityManager()
  entityManager: EntityManager;

  async initData() {
    const permission1 = new Permission();
    permission1.name = 'create_aaa';
    permission1.desc = '新增 aaa';

    const permission2 = new Permission();
    permission2.name = 'update_aaa';
    permission2.desc = '修改 aaa';

    const permission3 = new Permission();
    permission3.name = 'remove_aaa';
    permission3.desc = '删除 aaa';

    const permission4 = new Permission();
    permission4.name = 'query_aaa';
    permission4.desc = '查询 aaa';

    const permission5 = new Permission();
    permission5.name = 'create_bbb';
    permission5.desc = '新增 bbb';

    const permission6 = new Permission();
    permission6.name = 'update_bbb';
    permission6.desc = '修改 bbb';

    const permission7 = new Permission();
    permission7.name = 'remove_bbb';
    permission7.desc = '删除 bbb';

    const permission8 = new Permission();
    permission8.name = 'query_bbb';
    permission8.desc = '查询 bbb';

    const user1 = new User();
    user1.username = 'newking';
    user1.password = 'zjhQQsybzd';
    user1.permissions = [
      permission1, permission2, permission3, permission4
    ]

    const user2 = new User();
    user2.username = 'zjh';
    user2.password = 'zjhQQsybzd';
    user2.permissions = [
      permission5, permission6, permission7, permission8
    ]

    await this.entityManager.save([
      permission1,
      permission2,
      permission3,
      permission4,
      permission5,
      permission6,
      permission7,
      permission8
    ])

    await this.entityManager.save([
      user1,
      user2
    ]);
  }


  async login(user:LoginUserDto){
    const finduser = await this.entityManager.findOneBy(User,{
      username: user.username
    })

    if(!finduser){
      throw new HttpException('用户不存在',HttpStatus.ACCEPTED);
    }

    if(user.password !== finduser.password){
      throw new HttpException('密码错误',HttpStatus.ACCEPTED);
    }
  

    return user;
  }


  async findByUsername(username:string){
     
    const user = await this.entityManager.findOne(User,{
      where:{username},
      relations:{permissions:true}
    })
    
    return user;
    
  }

}
